﻿namespace IBTrader.Modules.HistoricalData
{
    using AxTWSLib;
    using IBTrader.Model;
    using IBTrader.Modules.Configuration;
    using IBTrader.Properties;
    using System;
    using System.IO;

    class File
    {
        private StreamWriter file = null;
        private string fileName;
        private DateTime lastDateTime;
        private readonly HistoricalData main;
        private readonly HistoricalContract contract;
        internal File(HistoricalData main, HistoricalContract contract)
        {
            this.main = main;
            this.contract = contract;
        }
        internal void End()
        {
            if (file != null && (fileName != FileName()|| main.Error.Failed))
            {
                file.Close();
                file = null;
                if (main.Cancelled || main.Error.Failed) new FileInfo(fileName).Delete();
                var fo = new FileInfo(FileName());
                if (fo.Exists && fo.Length == 0) fo.Delete();
            }
        }
        internal bool Start()
        {
            if (file == null)
            {
                fileName = FileName();
                var fi = new FileInfo(fileName);
                if (fi.Exists && fi.Length > 0) return false;
                file = new StreamWriter(fi.Open(FileMode.Create, FileAccess.Write, FileShare.ReadWrite));
            }
            return true;
        }
        internal void Write(_DTwsEvents_historicalDataEvent e)
        {
            var utc = new DateTime(1970, 1, 1, 0, 0, 0).AddSeconds(double.Parse(e.date));
            var now = Times.UtcToNow(utc);

            if (now < main.Contract.DateTime || now < lastDateTime) return;
            lastDateTime = now;
            file.WriteLine(string.Join(";", e.reqId, now.ToString(Times.DateTimeFormat), e.open, e.high, e.low, e.close, e.volume, e.wAP, e.hasGaps));
            contract.Percent = Math.Max(.01, contract.Percent);
        }
        private string FileName()
        {
            var folder = Settings.Default.BacklogFolder;
            if (!Directory.Exists(folder)) Directory.CreateDirectory(folder);
            return Path.Combine(folder, string.Format("{0} {1:" + Times.DateFormat + "} {2}.txt", main.Contract.Symbol, main.Contract.DateTime, contract.BarSize));
        }
    }
}
